package com.mysns.web.interceptor;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登录的拦截方法. 除了已登录之外, 有些应用还必须保证当前用户已通过邮箱认证才允许进行下一步操作.
 * 
 * @author zhouych
 */
public class SigninInterceptor extends HandlerInterceptorAdapter {
	
	private static Logger logger = LoggerFactory.getLogger(SigninInterceptor.class);

	/**
	 * 被限制访问的资源url
	 */
	private List<String> limitUrls;
	
	/**
	 * 登录页面
	 */
	private String loginView;
	
	/**
	 * 邮箱认证页面
	 */
	private String emailConfirmView;
	
	public void setLimitUrls(String[] limitUrls) {
		this.limitUrls = Arrays.asList(limitUrls);
	}

	public void setLoginView(String loginView) {
		this.loginView = loginView;
	}

	public void setEmailConfirmView(String emailConfirmView) {
		this.emailConfirmView = emailConfirmView;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		// 如果用户未登录
		if (request.getSession().getAttribute("current_user") == null) {
			for (String url : limitUrls) {
				if (request.getRequestURI().indexOf(url) != -1) {
					response.sendRedirect(request.getContextPath() + loginView);
					return false;
				}
			}
		}
		return true;
	}
}
